<template>
  <div class="listOne">
    <div class="left">
      <van-sidebar v-model="activekey">
        <van-sidebar-item
          :to="{ name: 'VueYimutianList', params: { id: item.id } }"
          v-for="item in categories"
          :key="item.id"
          :title="item.name"
        />
      </van-sidebar>
    </div>
    <div class="right">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadData"
      >
        <van-card
          @click="toDetail(i.id)"
          num="1"
          v-for="i in productsList"
          :key="i.id"
          :price="i.price"
          :desc="i.desc"
          :title="i.name"
          :thumb="i.coverImage | filterImage"
        />
      </van-list>
    </div>
  </div>
</template>

<script>
import { categoriesAPI } from '../service/categories';
import { RequestAPI } from '../service/product';

export default {
  name: 'VueYimutianList',

  data() {
    return {
      activekey: 0,
      productsList: [],
      page: 1,
      pages: 1,
      loading: false,
      finished: false,
      categories: [],
    };
  },

  mounted() {},
  async created() {
    const res1 = await categoriesAPI();
    this.categories = res1.data.data;
    this.activeKey = this.categories.findIndex(
      // eslint-disable-next-line comma-dangle
      (item) => item.id * 1 === this.$route.params.id * 1
    );
  },
  // 组件内的路由拦截，
  // 路由地址改变且组件被复用的时候调用
  beforeRouteUpdate(to, from, next) {
    // 下列三个都是初始化信息
    this.productsList = [];
    this.finished = false;
    this.page = 1;
    next();
    this.loadData();
    if (this.page > this.pages) {
      this.finished = true;
    }
  },
  methods: {
    async loadData() {
      this.loading = true;
      const res = await RequestAPI(this.page, this.$route.params.id);
      this.productsList.push(...res.data.data);
      this.pages = res.pages;
      this.page += 1;
      this.loading = false;
      if (this.page > this.pages) {
        this.finished = true;
      }
    },
    toDetail(id) {
      this.$router.push({
        name: 'VueYimutianDetail',
        params: { id },
      });
    },
  },
};
</script>

<style scoped>
.listOne {
  display: flex;
}
.right {
  /* height: 100%; */
  overflow: auto;
  flex: 1;
}
</style>
